package com.qyl.socket_upload.client;

import com.alibaba.fastjson.JSONObject;
import com.qyl.socket_upload.server.FileServer;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class FileClient {
    /**
     * 发送文件
     */
    public void sendFile(String path) throws Exception {
        File file = new File(path);
        //创建连接，创建文件输入流，网络输出流
        Socket socket = new Socket("127.0.0.1", FileServer.PORT);
        InputStream in = new FileInputStream(path);
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        Map<String, Object> req =  new HashMap<>();
        req.put("fileName", file.getName());
        req.put("id", 1);
        req.put("name", "qyl");
        req.put("contentType", file.length());
        //先发送文件给服务器
        out.writeUTF(JSONObject.toJSONString(req));
        out.flush();
        //读取本地文件，写入到网络输出流中
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len  = in.read(buffer)) != -1){
            out.write(buffer,0,len);
        }
        System.out.println("客户端发送完毕！");
    }

    public static void main(String[] args) throws Exception {
        new FileClient().sendFile("D:\\【无标题】.md");
    }
}
